package com.class5.springboot.util;

import java.io.*;
import java.text.ParseException;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.class5.springboot.util.exception.ServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;


/**
 * <p>文件处理类</p>
 * @author huangzongji
 *
 */
public class FileHelper {
	private static Log log = LogFactory.getLog(FileHelper.class);
	
	static private final int BUF_SIZE = 1024*10;
	
	// 保存的文件名，当上传文件为分块多次请求时，需要确保文件名唯一,
	private static Map<String,String> savedFileNameCache = new HashMap<String, String>();
	
	/**
	 * 上传文件
	 * @param is 文件输入流
	 * @param fullName 保存文件绝对路径
	 * @param isAppend 如果出现同名文件，是否追加
	 * @return
	 */
	public static boolean  uploadFile(InputStream is,String fullName,boolean isAppend){
		int chunkSize = 50*1024*1024;
		try {
			OutputStream bos = new FileOutputStream(fullName,isAppend);
			int bytesRead = 0;
			byte[] buffer = new byte[chunkSize];
			while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			bos.close();
			is.close();
			return true;
		} catch (Exception e) {
			log.error("上传文件时发生错误：", e);
			return false;
		}
	}
	
	/**
	 * 上传文件
	 * @param is 文件输入流
	 * @param fullName 保存文件绝对路径
	 * @return
	 */
	public static boolean uploadFile(InputStream is,String fullName){
		try {
			OutputStream bos = new FileOutputStream(fullName);
			int bytesRead = 0;
			byte[] buffer = new byte[BUF_SIZE];
			while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			bos.close();
			is.close();
			return true;
		} catch (Exception e) {
			log.error("上传文件时发生错误：", e);
			return false;
		}
	}
	
	/**
	 * 获取WebRoot绝对路径
	 * @return
	 */
	public static String getServerWebRoot(){
		String webRoot = "";//Config.getProperties("webapps_absolute_path");
		return webRoot;
	}
	
	/**
	 * 获取文件的后缀
	 * @param fileName
	 * @return
	 */
	public static String getSuffiex(String fileName){
		int index = fileName.lastIndexOf(".");
		String suffiex = "";
		if(index >= 0)
			suffiex= fileName.substring(index);
		return suffiex;
	}

	/**
	 * 下载文件
	 * @param fileName
	 * @param filePath
	 * @param response
	 * @throws IOException 
	 */
	public static void downloadFile(String fileName, String filePath, HttpServletResponse response) throws IOException {
		response.reset();
	    response.setContentType("application/x-msdownload;charset=gb2312");
//		System.out.println(new String(fileName.getBytes("gb2312"), "ISO8859-1"));
		response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
	    BufferedInputStream br = new BufferedInputStream(new FileInputStream(filePath));
	    byte[] buf = new byte[10*1024];
	    int len = 0;
		OutputStream out = response.getOutputStream();
		while((len = br.read(buf)) >0)
			out.write(buf,0,len);
	    br.close();
		out.flush();
		out.close();
	}

	/**
	 * 获取文件除去后缀后的名字
	 * @param fileName
	 * @return
	 */
	public static String getFileDisplayName(String fileName) {
		int index = fileName.lastIndexOf(".");
		if(index == -1)
			return fileName;
		String displayName = fileName.substring(0, index);
		return displayName;
	}

	/**
	 * MultipartFile上传
	 * @param mFile,directory(文件夹路径)
	 * @return 文件路径,文件名称
	 */
	public static JSONObject MultipartFileToFile(MultipartFile mFile, String directory){
		JSONObject json = new JSONObject();
		InputStream input = null;
		String prefix = "";
		String fullPath = "";
		String fileName = "";
		try {
			input = mFile.getInputStream();
			fileName = mFile.getOriginalFilename();
			prefix = getSuffiex(fileName);
			createDirectory(directory);
			fullPath = directory + StringUtils.getUUID() + prefix;
			uploadFile(input,fullPath);
		}catch (FileNotFoundException e) {
			throw new ServiceException("找不到文件夹!");
		}catch (IOException e) {
			throw new ServiceException("文件上传失败!");
		}
		json.put("filePath",fullPath);
		json.put("fileName",fileName);
		return json;
	}

	/**
	 * <p>获取文件系统保存的文件名 "xxxxxx_20180809.jpg"</p>
	 * @param filename
	 * @return
	 */
	private static String getSavedFileName(String filename){
		StringBuffer sb = new StringBuffer();
		String suffic = filename.substring(filename.lastIndexOf("."));
		String file = filename.substring(0,filename.lastIndexOf("."));
		sb.append(file).append("_").append(DateUtils.getDay1());
		sb.append(suffic);
		return sb.toString();
	}
	
	/**
	 * 删除附件
	 * @param relativePath
	 * @param filename
	 */
	public static boolean deleteFile(String relativePath,String filename){
		StringBuffer sb = new StringBuffer(1024);
		sb.append(File.separator).append(relativePath).append(File.separator).append(filename);
		log.debug("删除文件路径："+sb.toString());
		// 删除文件
		return new File(sb.toString()).delete();
	}

	/**
	 * 创建文件夹
	 * @param file_path
	 */
	public static void createDirectory(String file_path){
		File file = new File(file_path);
		if(!file.exists()){
			file.mkdirs();
		}
	}

	/**
	 * 获取文件大小
	 * @param file_path
	 */
	public static long getFileLength(String file_path){
		File file = new File(file_path);
		if (file.exists() && file.isFile()) {
			return file.length();
		}
		return 0l;
	}

	public static void main(String[] args) {
		System.out.println(FileHelper.getSavedFileName("C:\\upload\\test\\eef1e141d6ff44ed821c3947312d8103.jpg"));

	}
}